import React,{useState} from 'react';
import { Form, Input, Button, Toast } from 'antd-mobile';
import ReactLogo from '../assets/react.svg';
import styles from './LoginPage.module.scss';
import { useNavigate } from 'react-router-dom';
import { useUserContext } from '@/context/UserContext';
import { useDispatch } from 'react-redux';
import { fetchLogin } from '@/store/modules/user';

const LoginPage = () => {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const { configDefault } = useUserContext(); // 获取用户状态
  const navigate = useNavigate();

  // 修改根元素变量（推荐）
  document.documentElement.style.setProperty('--adm-color-primary', 'rgb(105, 174, 120)');

  const onFinish = async (values) => {
    // // console.log('Received values of form: ', values);
    setLoading(true);

    try {
      const result = await dispatch(fetchLogin(values));
      // console.log('result', result)
      if (result.success) {
        localStorage.setItem('mobile', values.mobile); // 存储手机号
        navigate("/main", { state: configDefault.tabDefault });
      } else {
        Toast.show({
          content: result.error.response.data.message ? result.error.response.data.message : '登录失败，请检查手机号或验证码',
          afterClose: () => {
            console.log('after')
          },
        })
      }
    } catch (error) {
      console.error("Login error:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.logoContainer}>
        <img src={ReactLogo} alt="React Logo" className={styles.logo} />
      </div>
      <Form
        initialValues={{
          mobile: localStorage.getItem('mobile') || '', // 设置默认值
        }}
        layout="vertical"
        onFinish={onFinish}
        footer={
          <Button loading={loading} block type="submit" color='primary' loadingText='登录中' size="large">
            登录
          </Button>
        }
      >
        <Form.Item
          name="mobile"
          label="手机号"
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号格式'
            }
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item
          name="code"
          label="验证码"
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <Input placeholder="请输入验证码" type="text" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginPage;
